package livesun.justiceeternal.db.love;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.query.QueryBuilder;

import livesun.justiceeternal.db.LoveBeanDao;
import livesun.justiceeternal.db.task.AbsTemplateDbTask;
import livesun.justiceeternal.utils.HandlerFactory;

public class LoveSaveTask<T>  extends AbsTemplateDbTask<LoveBean> {

    private final LoveBean saveBean;

    public LoveSaveTask(Class<? extends LoveBean> t, LoveBean saveBean) {
        super(t);
        this.saveBean = saveBean;
    }

    @Override
    public void onTaskExecute(AbstractDao<LoveBean, ?> dao) {
        if (dao != null) {
            try {
                LoveBean oldUser = getUserInfoFromCache(saveBean, dao);
                if (oldUser != null)
                {
                    saveBean.setId(oldUser.getId());
                }
                dao.save(saveBean);
                onSaveFinished(saveBean);
            } catch (Throwable e) {
                e.printStackTrace();
                onFail(e.getMessage());
            }
        }

        return;
    }

    public LoveBean getUserInfoFromCache(LoveBean saveBean,AbstractDao<LoveBean, ?> dao)
    {
        QueryBuilder<LoveBean> query = dao.queryBuilder().where(LoveBeanDao.Properties.ItemId.eq(saveBean.getItemId()))
                .orderDesc(LoveBeanDao.Properties.SaveTime);
        return  query.unique();
    }

    private void onSaveFinished(final LoveBean loveBean) {
        HandlerFactory.main().post(new Runnable() {
            @Override
            public void run() {
                onSaveSuccess(loveBean);
            }
        });
    }

    public void onSaveSuccess(LoveBean loveBean){

    }

    public void onSaveFailed(String error){

    }

    private void onFail(final String error) {
        HandlerFactory.main().post(new Runnable() {
            @Override
            public void run() {
                onSaveFailed(error);
            }
        });
    }
}
